<template>
  <div class="app-container">
    <div
      v-show="!modifyInfo.visible && !detailsInfo.visible"
      v-if="$permission('azDrug:list')"
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </new-page-filter>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">

          <template v-slot:filter-uploadProduct>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-exprotExcel>
            <el-button @click="exportExcel">导出excel</el-button>
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true"
            >偏好设置
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :checkBox="true"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassOtherName"
        @sortChange="sortChange"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template
          v-slot:col-commonName="scope"
        >
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.commonName || '-'
          }}</span>
        </template>
      </table-container>
    </div>
    <!--偏好 -->
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <!-- 详情-->
    <equipment-archives-details
      v-if="detailsInfo.visible"
      v-model:visible="detailsInfo.visible"
      :title="detailsInfo.title"
      :id="detailsInfo.id"
      @returnBack="getList"
    />
    <!-- 新增或修改 -->
    <equipment-archives-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
      :id="modifyInfo.id"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />

    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <chose-printer
      v-model:visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
  </div>
</template>

<script setup name="drug">
import EquipmentArchivesModify from './modify'
import EquipmentArchivesDetails from './details'
import axios from 'axios'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import {
  getDrugCustomizeList,
} from '@/api/core'
import {
  exportAccessoriesArchives,
} from '@/api/equipment'
import { ElMessage, ElLoading } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub.js'
const { proxy } = getCurrentInstance()

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {
      type: {
        asTbName: 'core_product_new',
        columnName: '`type`',
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '4',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    // {
    //   type: 'button',
    //   label: '新增',
    //   event: create,
    //   show: proxy.$permission('accessoriesArchives:add'),
    // },
    // {
    //   type: 'button',
    //   label: '下载模板',
    //   event: downloadTemplate,
    //   show: proxy.$permission('accessoriesArchives:download'),
    // },
    // {
    //   type: 'slot',
    //   value: 'uploadProduct',
    //   show: proxy.$permission('accessoriesArchives:import'),
    // },
    // {
    //   type: 'slot',
    //   label: '导出excel',
    //   value: 'exprotExcel',
    //   show: proxy.$permission('accessoriesArchives:export'),
    // },
  ],
})

const clearType = ref(true)
const slipSelectRequest = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '90',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('azDrug:update'),
      },
    ],
  },
})
// 表单相关
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const detailsInfo = ref({
  visible: false,
  id: '',
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const preferenceInfo = ref({
  visible: false,
})
const uploadInfo = ref({
  action:
    axios.defaults.baseURL + '/asset/setting/accessoriesArchives/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '导出',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

const canRun = computed(() => {
  return (
    tableInfo.value.selections.length > 0 &&
    tableInfo.value.selections.filter((item) => item.status === 1).length === 0
  )
})
const canStop = computed(() => {
  return (
    tableInfo.value.selections.length > 0 &&
    tableInfo.value.selections.filter((item) => item.status === 0).length === 0
  )
})
onBeforeMount(() => {
  let obj = {
    commonName: {
      label: '药品名称',
      value: 'commonName',
      componentType: 'input',
      type: 'slot',
      show: false,
      hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'enabled_type',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
})
const pageInfo = (obj) => {
  page.value = obj
}
const exportExcelList = () => {
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  exportAccessoriesArchives(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function handleClose() {
  dialogInfo.value.visible = false
}
// 获取列表
const getList = () => {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 创建
function create() {
  modifyInfo.value.id = null
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增药品'
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改药品'
}

const showDetail = (row) => {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.value.id = row.id
  detailsInfo.value.visible = true
}
const tableRowClassOtherName = ({ row }) => {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
const handleEvent = (event, data) => {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
const getIds = (row = undefined) => {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((row) => row.id)
  }
  return ids
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
const getCustomize = (slipSelect = true) => {
  let param = {
    tableKey:
      'coreDrugList-com.slip.spd.entity.vo.asset.settings.AccessoriesArchivesVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = slipSelect
      tableInfo.value.api = getDrugCustomizeList
      getList()
    }
  })
}

const sortChange = (column) => {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}

const setPreferenceCallback = async (obj) => {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
const exportExcel = () => {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
const returnModify = () => {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
function downloadTemplate() {
  exportTemplateExcel('accessories_archives_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}

const uploadError = (err) => {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
const beforeProductUpload = (file) => {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    $message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    $message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
const importProduct = (resp) => {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
const handlePrinterCallBack = (printer) => {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
const advancedSearchCallback = async (obj) => {
  filterInfo.value.query.queryMap = {}
  obj.queryDtoList.push({
    fieldName: 'type',
    queryCategory: 'AND',
    queryType: 'EQUALS',
    value: 2,
  })
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
</script>

<style scoped></style>
